import { getDict } from '@/controllers/API/common'
import { create } from 'zustand'
/**
 * 后端返回的通用字典信息，以支持：
 * 1、/dict_detail/options： category(类型)，icon(图标)
 */
type DictType = {
  id: number | string
  value: string
  label: string
  create_time?: string
  dictionary_code?: string
  sort?: number
  states?: boolean
  update_time?: string
}

type BackendDictState = {
  category: DictType[]
  icon: DictType[]
}

type Actions = {
  loadDictOptions: (type: 'category' | 'icon' | string) => Promise<DictType[]>
}

export const useDictStore = create<BackendDictState & Actions>(set => ({
  category: [],
  icon: [],
  loadDictOptions: type => {
    if (useDictStore.getState()[type] && useDictStore.getState()[type].length) {
      return Promise.resolve(useDictStore.getState()[type].slice())
    }
    return getDict(type).then(res => {
      const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      if (userInfo?.user_name === 'admin') {
        set({
          [type]: res ? res.slice() : []
        })
      } else {
        // 过滤掉 id 为 100 和 101 的项目
        const filteredRes = res.filter(item => ![100, 101].includes(item.id))
        set({
          [type]: filteredRes.slice()
        })
      }
      console.log('load backend dict: ', type)
      return res || []
    })
  }
}))
